﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Drawing;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SysMonitor
{
    public partial class Form1 : Form
    {
        #region Attributes

        protected Thread MonitorThread = null;
        protected delegate void ListViewDelGate(List<string> vals);

        private Object thisLock = new Object();//用于lock(thisLock)

        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        #region Form

        private void Form1_Load(object sender, EventArgs e)
        {
            if (CheckService()) this.cbService.Checked = true;
            else this.cbService.Checked = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            if (this.timer1.Enabled == true)
            {
                if (MessageBox.Show("正在进行监控，确认要退出吗？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                {
                    return;
                }
            }
            if (MonitorThread != null && MonitorThread.IsAlive)
            {
                try
                {
                    MonitorThread.Abort();
                }
                catch
                {
                }
            }
            e.Cancel = false;
        }

        #endregion

        #region Button

        private void btnStart_Click(object sender, EventArgs e)
        {
            bool issel=false;

            #region 检查监控对象

            if (this.cbDisk.Checked) 
            {
                GlobalAtrrib.myInfo.Disk = true;
                issel=true;
            }
            else GlobalAtrrib.myInfo.Disk = false;
            if (this.cbMem.Checked) 
            {
                GlobalAtrrib.myInfo.Memory = true;
                issel=true;
            }
            else GlobalAtrrib.myInfo.Memory = false;
            if (this.cbCPU.Checked) 
            {
                GlobalAtrrib.myInfo.CPU = true;
                issel=true;
            }
            else GlobalAtrrib.myInfo.CPU = false;

            if (!issel)
            {
                MessageBox.Show("必须选择一个监控对象");
                return;
            }

            #endregion

            InitListView();
            MonitorThread = new Thread(new ThreadStart(myMonitor));
            MonitorThread.Start();
            this.timer1.Start();
            this.timer1.Interval = (int)this.nudInterval.Value * 1000;
            this.btnStart.Enabled = false;
            this.btnStop.Enabled = true;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.timer1.Stop();
            if (MonitorThread != null && MonitorThread.IsAlive)
            {
                try
                {
                    MonitorThread.Abort();
                }
                catch
                {
                }
            }
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
        }

        #endregion

        #region CheckBox

        private void cbService_Click(object sender, EventArgs e)
        {
            if (this.cbService.Checked)
            {
                CreateService();
            }
            else
            {
                DeleteService();
            }
        }

        #endregion

        #region ListView

        private void InitListView()
        {
            this.lvResult.BeginUpdate();
            this.lvResult.Clear();
            this.lvResult.View = View.Details;
            this.lvResult.GridLines = true;
            this.lvResult.Columns.Add("日期", 80, HorizontalAlignment.Center);
            this.lvResult.Columns.Add("时间", 80, HorizontalAlignment.Center);
            if (GlobalAtrrib.myInfo.Disk)
            {
                DriveInfo[] mydrivers = DriveInfo.GetDrives();
                foreach (DriveInfo mydriver in mydrivers)
                {
                    if (mydriver.DriveType == DriveType.Fixed) this.lvResult.Columns.Add(mydriver.RootDirectory.Name + "(GB)", 120, HorizontalAlignment.Center);
                }
            }
            if (GlobalAtrrib.myInfo.Memory) this.lvResult.Columns.Add("内存(MB)", 120, HorizontalAlignment.Center);
            if (GlobalAtrrib.myInfo.CPU) this.lvResult.Columns.Add("CPU", 50, HorizontalAlignment.Center);
            this.lvResult.EndUpdate();
        }

        #endregion

        #region Thread&DeleGate

        private void myMonitor()
        {
            this.lvResult.Invoke(new ListViewDelGate(AddItem), new object[] { Monitor.Start() });
        }

        private void AddItem(List<string> vals)
        {
            lock (thisLock)
            {
                ListViewItem item = new ListViewItem();
                item.SubItems[0].Text = DateTime.Now.ToString("yyyy-MM-dd");
                foreach (string val in vals)
                {
                    item.SubItems.Add(val);
                }
                this.lvResult.Items.Add(item);
            }
        }

        #endregion

        #region Timer

        private void timer1_Tick(object sender, EventArgs e)
        {
            //if (MonitorThread == null || !MonitorThread.IsAlive)
            //{
                MonitorThread = new Thread(new ThreadStart(myMonitor));
                MonitorThread.Start();
            //}
        }

        #endregion

        #region ToolStripMenuItem

        private void toolStripMenuItem_ExportSelect_Click(object sender, EventArgs e)
        {
            this.saveFileDialog1.ValidateNames = true;
            this.saveFileDialog1.Filter = "日志文件(*.log)|*.log|CSV文件(*.csv)|*.csv|Excel文件(*.xls)|*.xls";
            this.saveFileDialog1.FilterIndex = 1;
            this.saveFileDialog1.DefaultExt = "log";
            this.saveFileDialog1.FileName = "";
            this.saveFileDialog1.AddExtension = true;
            if (this.saveFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            if (this.saveFileDialog1.FileName.EndsWith(".xls"))
            {
                if (Export.Export2Excel(lvResult, lvResult.SelectedItems, this.saveFileDialog1.FileName))
                {
                    MessageBox.Show("导出成功");
                }
                else
                {
                    MessageBox.Show("操作失败");
                    return;
                }
            }
            else
            {
                if (Export.Export2Txt(lvResult, lvResult.SelectedItems, this.saveFileDialog1.FileName))
                {
                    MessageBox.Show("导出成功");
                }
                else
                {
                    MessageBox.Show("操作失败");
                    return;
                }
            }
        }

        private void toolStripMenuItem_ExportAll_Click(object sender, EventArgs e)
        {
            this.saveFileDialog1.ValidateNames = true;
            this.saveFileDialog1.Filter = "日志文件(*.log)|*.log|CSV文件(*.csv)|*.csv|Excel文件(*.xls)|*.xls";
            this.saveFileDialog1.FilterIndex = 1;
            this.saveFileDialog1.DefaultExt = "log";
            this.saveFileDialog1.FileName = "";
            this.saveFileDialog1.AddExtension = true;
            if (this.saveFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            if (this.saveFileDialog1.FileName.ToLower().EndsWith(".xls"))
            {
                if (Export.Export2Excel(lvResult, this.saveFileDialog1.FileName))
                {
                    MessageBox.Show("导出成功");
                }
                else
                {
                    MessageBox.Show("操作失败");
                    return;
                }
            }
            else if (this.saveFileDialog1.FileName.ToLower().EndsWith(".csv"))
            {
                if (Export.Export2CSV(lvResult, this.saveFileDialog1.FileName))
                {
                    MessageBox.Show("导出成功");
                }
                else
                {
                    MessageBox.Show("操作失败");
                    return;
                }
            }
            else
            {
                if (Export.Export2Txt(lvResult, this.saveFileDialog1.FileName))
                {
                    MessageBox.Show("导出成功");
                }
                else
                {
                    MessageBox.Show("操作失败");
                    return;
                }
            }
        }

        #endregion

        #region Method(Service)

        private bool CheckService()
        {
            ServiceController[] sc = ServiceController.GetServices();

            foreach (ServiceController service in sc)
            {
                if (service.ServiceName.ToUpper() == GlobalAtrrib.ServiceName.ToUpper()) return true;
                service.Dispose();
            }

            sc = null;            

            return false;
        }

        private bool CreateService()
        {
            if (CheckService())
            {
                MessageBox.Show("服务已存在");
                return false;
            }

            Process process = new Process();
            try
            {
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = "sc.exe";
                process.StartInfo.Arguments = " create " + GlobalAtrrib.ServiceName + " binPath= \"" + Application.ExecutablePath + " -service\" type= \"share\" type= \"interact\" obj= \"LocalSystem\" start= \"auto\"";
                process.StartInfo.UseShellExecute = false;
                process.Start();
                string Result = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                process.Close();
            }

            if (!CheckService())
            {
                MessageBox.Show("安装失败");
                return false;
            }

            ServiceController sc = new ServiceController(GlobalAtrrib.ServiceName);
            try
            {
                sc.Start();
                sc.WaitForStatus(ServiceControllerStatus.Running);
                MessageBox.Show("安装完成。服务状态:" + sc.Status.ToString());
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            catch (Exception)
            {
                MessageBox.Show("系统错误");
                return false;
            }
            finally
            {
                sc.Dispose();
            }

            return true;
        }

        private bool DeleteService()
        {
            if (!CheckService())
            {
                MessageBox.Show("服务不存在");
                return false;
            }

            ServiceController sc = new ServiceController(GlobalAtrrib.ServiceName);
            try
            {
                if (sc.Status != ServiceControllerStatus.Stopped) sc.Stop();
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            catch (Exception)
            {
                MessageBox.Show("系统错误");
                return false;
            }
            finally
            {
                sc.Dispose();
            }

            Process process = new Process();
            try
            {
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = "sc.exe";
                process.StartInfo.Arguments = " delete " + GlobalAtrrib.ServiceName;
                process.StartInfo.UseShellExecute = false;
                process.Start();
                string Result = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                process.Close();
            }

            if (CheckService())
            {
                MessageBox.Show("卸载失败");
                return false;
            }
            else
            {
                MessageBox.Show("卸载完成");
                return true;
            }
        }

        #endregion

    }

    public class CustomListView : ListView
    {
        public CustomListView()
        {
            SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            UpdateStyles();
        }
    }
}
